package com.es.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPObject;
import com.es.domain.Book;
import jakarta.json.JsonNumber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @email: fahoud@163.com
 * @author: duzifeng
 * @date: 2023/6/1
 * @time: 10:28
 * Description:
 */
@RestController
@Slf4j
public class EsTestController {
    @Resource
    private ElasticsearchClient elasticsearchClient;

    @PostMapping("/insertBookProduct")
    public Map<String, Object> insertBookProduct(@RequestBody Map<String, Object> param) throws IOException {
        Book book = JSON.parseObject(JSON.toJSONString(param), Book.class);
        log.info("book: {} ", book);
        IndexResponse book1 = elasticsearchClient.index(new IndexRequest.Builder<Book>()
                .index("book")
                .id(book.getId())
                .document(book)
                .build());
        HashMap<String, Object> result = new HashMap<>();
        result.put("res", book1.toString());

        return result;
    }

    @GetMapping("/getBook")
    public Map<String, Object> getBook(String param) throws IOException {
        SearchResponse<Book> book = elasticsearchClient.search(new SearchRequest.Builder()
                .index("book")
                .query(q -> q.term(t -> t.field("title").value(param)))
                .build(), Book.class);
        log.info(book.toString());

        List<Hit<Book>> hits = book.hits().hits();
        for (Hit<Book> hit : hits) {
            log.info("book info: {}", hit.source());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("list", hits.stream().map(Hit::source).collect(Collectors.toList()));
        return result;
    }
}
